import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { persistReducer, persistStore } from "redux-persist";
// import session from "redux-persist/lib/storage/session"; // sessionStorage
import storage from "redux-persist/lib/storage"; // localStorage

// 引入拆分出去的切片模块
import app from "./modules/app";
import user from "./modules/user";

// 配置 persist 的相关使用
// const persistConfig = {
//   key: "root", // 持久化数据到本地存储中的 key 名 "xxx:root",
//   storage: storage, // 使用 localStorage | sessionStorage
//   blacklist: ["user"], // 白名单
// };

// 生成 persistReducer
// const persistedReducer = persistReducer(persistConfig, rootReducer);

const rootReducer = combineReducers({
  app: persistReducer({ key: "app", storage: storage }, app),
  user: persistReducer(
    { key: "user", storage: storage, blacklist: ["menuItems"] },
    user
  ),
});

// 生成 store
const store = configureStore({
  // reducer: {
  //   app,
  // },
  reducer: rootReducer,
  // 配置不需要做序列化检查，主要处理使用了 redux-persist 后报错的一个小问题
  middleware: (getDefaultMiddleware) => {
    return getDefaultMiddleware({
      serializableCheck: false,
    });
  },
});

// redux store  store.getState  store.subscribe  store.dispatch
// 定义State和dispatch类型  从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

// 使用 persistStore 方法，生成 persistor，用于入口文件中 PersistGate 组件的 同名属性
export const persistor = persistStore(store);
export default store;
